package game

import (
	"time"

	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
	"github.com/flipped-aurora/gin-vue-admin/server/model/game"
	gameReq "github.com/flipped-aurora/gin-vue-admin/server/model/game/request"
	gameRes "github.com/flipped-aurora/gin-vue-admin/server/model/game/response"
	"github.com/flipped-aurora/gin-vue-admin/server/utils"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type BsSignUpApi struct{}

// CreateSignUp
// @Tags      BsSignUp
// @Summary   创建报名
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      game.BsSignUp                  true  "api路径, api中文描述, api组, 方法"
// @Success   200   {object}  response.Response{msg=string}  "创建报名"
// @Router    /signUp/createSignUp [post]
func (s *BsSignUpApi) CreateSignUp(c *gin.Context) {
	var param game.BsSignUp
	err := c.ShouldBindJSON(&param)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(param, utils.ApiVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	gi, err := projectGameInfoService.GetProjectGameInfoById(int(param.ProjectId), int(param.GameinfoId))
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	total, err := signUpService.CountSignUp(game.BsSignUp{ProjectId: param.ProjectId, GameinfoId: param.GameinfoId, AuthorityId: param.AuthorityId})
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if param.AuthorityId == 888 {
		if total >= int64(gi.PlayerNum) {
			response.FailWithMessage("已达到数量上限", c)
			return
		}
	}
	param.CreateTime = time.Now()
	param.UpdateTime = time.Now()
	err = signUpService.CreateSignUp(param)
	if err != nil {
		global.GVA_LOG.Error("创建失败!", zap.Error(err))
		response.FailWithMessage("创建失败", c)
		return
	}
	response.OkWithMessage("创建成功", c)
}

// DeleteSignUp
// @Tags      BsSignUp
// @Summary   删除报名
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      game.BsSignUp                  true  "Id"
// @Success   200   {object}  response.Response{msg=string}  "删除报名"
// @Router    /signUp/deleteSignUp [delete]
func (s *BsSignUpApi) DeleteSignUp(c *gin.Context) {
	var param game.BsSignUp
	err := c.ShouldBindJSON(&param)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(param, utils.IdVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = signUpService.DeleteSignUp(param)
	if err != nil {
		global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败", c)
		return
	}
	response.OkWithMessage("删除成功", c)
}

// GetSignUpList
// @Tags      BsSignUp
// @Summary   分页获取报名列表
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      gameReq.SignUpParams                               true  "分页获取报名列表"
// @Success   200   {object}  response.Response{data=response.PageResult,msg=string}  "分页获取报名列表,返回包括列表,总数,页码,每页数量"
// @Router    /signUp/getSignUpList [post]
func (s *BsSignUpApi) GetSignUpList(c *gin.Context) {
	var pageInfo gameReq.SignUpParams
	err := c.ShouldBindJSON(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(pageInfo.PageInfo, utils.PageInfoVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	list, total, err := signUpService.GetSignUpList(pageInfo.BsSignUp, pageInfo.PageInfo, pageInfo.OrderKey, pageInfo.Desc)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
		return
	}
	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     pageInfo.Page,
		PageSize: pageInfo.PageSize,
	}, "获取成功", c)
}

// GetSignUpOrderList
// @Tags      BsSignUp
// @Summary   分页获取排名列表
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      gameReq.SignUpParams                               true  "分页获取排名列表"
// @Success   200   {object}  response.Response{data=response.PageResult,msg=string}  "分页获取排名列表,返回包括列表,总数,页码,每页数量"
// @Router    /signUp/GetSignUpOrderList [post]
func (s *BsSignUpApi) GetSignUpOrderCountryList(c *gin.Context) {
	var pageInfo gameReq.SignUpParams
	err := c.ShouldBindJSON(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(pageInfo.PageInfo, utils.PageInfoVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	list, total, err := signUpService.GetSignUpCountryOrderList(pageInfo.BsSignUp, pageInfo.PageInfo, pageInfo.OrderKey, pageInfo.Desc)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
		return
	}
	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     pageInfo.Page,
		PageSize: pageInfo.PageSize,
	}, "获取成功", c)
}

func (s *BsSignUpApi) GetSignUpOrderOwnList(c *gin.Context) {
	var pageInfo gameReq.SignUpParams
	err := c.ShouldBindJSON(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(pageInfo.PageInfo, utils.PageInfoVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	list, total, err := signUpService.GetSignUpOwnOrderList(pageInfo.BsSignUp, pageInfo.PageInfo, pageInfo.OrderKey, pageInfo.Desc)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
		return
	}
	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     pageInfo.Page,
		PageSize: pageInfo.PageSize,
	}, "获取成功", c)
}

// GetSignUp
// @Tags      BsSignUp
// @Summary   根据id获取api
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      game.BsSignUp                                   true  "根据id获取报名记录"
// @Success   200   {object}  response.Response{data=gameRes.BsSignUpResponse}  "根据id获取报名,返回包括api详情"
// @Router    /signUp/getSignUp [get]
func (s *BsSignUpApi) GetSignUp(c *gin.Context) {
	var param game.BsSignUp
	err := c.ShouldBindJSON(&param)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(param, utils.ApiVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	userId := utils.GetUserID(c)
	signUp, err := signUpService.GetSignUp(int(userId), int(param.GameinfoId), int(param.ProjectId))
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
		return
	}
	response.OkWithDetailed(gameRes.BsSignUpResponse{SignUp: signUp}, "获取成功", c)
}

// UpdateSignUp
// @Tags      BsSignUp
// @Summary   修改报名信息
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      game.BsSignUp                  true  "api路径, api中文描述, api组, 方法"
// @Success   200   {object}  response.Response{msg=string}  "修改报名信息"
// @Router    /signUp/updateSignUp [put]
func (s *BsSignUpApi) UpdateSignUp(c *gin.Context) {
	var param game.BsSignUp
	err := c.ShouldBindJSON(&param)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(param, utils.ApiVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = signUpService.UpdateSignUp(param)
	if err != nil {
		global.GVA_LOG.Error("修改失败!", zap.Error(err))
		response.FailWithMessage("修改失败", c)
		return
	}
	response.OkWithMessage("修改成功", c)
}

// UpdateScore
// @Tags      BsSignUp
// @Summary   修改报名信息
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      game.BsSignUp                  true  "api路径, api中文描述, api组, 方法"
// @Success   200   {object}  response.Response{msg=string}  "修改报名信息"
// @Router    /signUp/updateScore [put]
func (s *BsSignUpApi) UpdateScore(c *gin.Context) {
	var param game.BsSignUp
	err := c.ShouldBindJSON(&param)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(param, utils.ApiVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	// userId := utils.GetUserID(c)
	wholeParam, err := signUpService.GetSignUp(int(param.UserId), int(param.GameinfoId), int(param.ProjectId))
	if err != nil {
		global.GVA_LOG.Error("修改失败!", zap.Error(err))
		response.FailWithMessage("修改失败", c)
		return
	}
	wholeParam.Score = param.Score
	wholeParam.Status = 2
	err = signUpService.UpdateSignUp(wholeParam)
	if err != nil {
		global.GVA_LOG.Error("修改失败!", zap.Error(err))
		response.FailWithMessage("修改失败", c)
		return
	}
	// 更新比赛状态
	total, err := signUpService.CountSignUp(game.BsSignUp{ProjectId: param.ProjectId, GameinfoId: param.GameinfoId, AuthorityId: 888})
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	luruTotal, err := signUpService.CountSignUp(game.BsSignUp{ProjectId: param.ProjectId, GameinfoId: param.GameinfoId, AuthorityId: 888, ExcludeStatus: 1})
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if total == luruTotal {
		projectGameInfo, err := projectGameInfoService.GetProjectGameInfoById(int(param.ProjectId), int(param.GameinfoId))
		if err != nil {
			response.FailWithMessage(err.Error(), c)
			return
		}
		projectGameInfo.Status = 3
		err = projectGameInfoService.UpdateProjectGameInfo(projectGameInfo)
		if err != nil {
			response.FailWithMessage(err.Error(), c)
			return
		}
		// 更新排名表
		sps, _, err := signUpService.GetSignUpList(game.BsSignUp{ProjectId: param.ProjectId, GameinfoId: param.GameinfoId, AuthorityId: 888}, request.PageInfo{Page: 1, PageSize: 100}, "score", true)
		if err != nil {
			response.FailWithMessage(err.Error(), c)
			return
		}
		scores := sps.([]game.BsSignUp)
		for i := 0; i < len(scores); i++ {

			err = rankService.CreateRank(
				game.BsRank{
					ProjectId:  scores[i].ProjectId,
					GameinfoId: scores[i].GameinfoId,
					UserId:     scores[i].UserId,
					Rank:       uint(i + 1),
					Username:   scores[i].Username,
					Country:    scores[i].UserCountry,
				})
			if err != nil {
				response.FailWithMessage(err.Error(), c)
				return
			}
		}
	}
	response.OkWithMessage("修改成功", c)
}
